package com.smartfarm.service;

import com.smartfarm.domain.task.Task;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任务管理器
 */
public class TaskManager {
    private final Map<String, Task> tasks = new HashMap<>();
    private final Map<String, List<Task>> equipmentTasks = new HashMap<>();

    public void createTask(Task task) {
        tasks.put(task.getTaskId(), task);
        // 为每个设备分配任务
        for (String equipmentId : task.getEquipmentIds()) {
            equipmentTasks.computeIfAbsent(equipmentId, k -> new ArrayList<>()).add(task);
        }
        System.out.println("Created new task: " + task.getTaskName());
    }

    public void updateTaskStatus(String taskId, String status, double completionRate) {
        Task task = tasks.get(taskId);
        if (task != null) {
            task.setStatus(status);
            task.setCompletionRate(completionRate);
            System.out.println("Updated task status: " + task.getTaskName() + " - " + status + " (" + completionRate + "%)");
        }
    }

    public List<Task> getEquipmentTasks(String equipmentId) {
        return equipmentTasks.getOrDefault(equipmentId, new ArrayList<>());
    }

    public Task getTask(String taskId) {
        return tasks.get(taskId);
    }

    public List<Task> getAllTasks() {
        return new ArrayList<>(tasks.values());
    }

    public void removeTask(String taskId) {
        Task task = tasks.remove(taskId);
        if (task != null) {
            for (String equipmentId : task.getEquipmentIds()) {
                List<Task> equipmentTaskList = equipmentTasks.get(equipmentId);
                if (equipmentTaskList != null) {
                    equipmentTaskList.remove(task);
                }
            }
            System.out.println("Removed task: " + task.getTaskName());
        }
    }
} 